package code.google.controller.search;

import android.os.AsyncTask;
import code.google.controller.interfaces.ISearchController;
import code.google.gui.fragments.adapter.SearchResultAdapter;
import code.google.gui.interfaces.ISearchFragment;
import code.google.model.groove.GrooveClient;
import code.google.model.groove.util.SearchResult;
import code.google.model.util.ModelProvider;
import code.google.model.util.interfaces.IGrooveClientCreationCallback;
import code.google.model.util.interfaces.ISong;

public class StreamSearchController implements ISearchController, IGrooveClientCreationCallback {

	private ISearchFragment fragment;
	private GrooveClient client;
	
	public StreamSearchController(ISearchFragment fragment){
		this.fragment = fragment;
		ModelProvider.getInstance().getGrooveClient(this);
	}
	
	public void doSearch(String query){
		if(client != null){
			new GrooveClientQueryTask(this).execute(query);
		}
	}
	
	public void playSong(ISong song){
		fragment.dispensePlay(song);
	}
	
	
	private class GrooveClientQueryTask extends
			AsyncTask<String, Void, SearchResult> {


		private ISearchController controller;

		public GrooveClientQueryTask(ISearchController controller) {
			this.controller = controller;
		}

		@Override
		protected SearchResult doInBackground(String... params) {
			return client.getResultsFromSearch(params[0]);
		}

		@Override
		protected void onPostExecute(SearchResult result) {
			fragment.setSearchResultAdapter(new SearchResultAdapter(result.getSongs(), fragment));
		}
	}

	@Override
	public void onClientCreationComplete(GrooveClient client) {
		this.client = client;
	}
}
